package Longing;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/*
 * @Author 枫城
 * 模拟银行转账
 *  关键，将JDBC的自动提交改为手动提交
    connection.setAutoCommit(false);
    * 事务提交
    connection.commit();
    * 事务回滚
    connection.rollback();
 **/
public class demo5 {
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://192.168.10.132:3306/learn_JDBC?useUnicode=true&characterEncoding=utf-8";
        String user = "root";
        String password = "123456";
        try {
            Class.forName("com.mysql.jdbc.Driver");


            connection = DriverManager.getConnection(url,user,password);

            // 禁止自动提交
            connection.setAutoCommit(false);

            String sql = "update user set combat_value = combat_value - ?  where user_id = ?";

            ps = connection.prepareStatement(sql);

            // 传输战力值
            ps.setString(1, "100");
            ps.setInt(2, 20001);

            int count = ps.executeUpdate();

            String sql1 = "update user set combat_value = combat_value + ? where user_id = ?";

            ps = connection.prepareStatement(sql1);

            ps.setString(1, "100");
            ps.setInt(2,20005);

            count += ps.executeUpdate();

            System.out.println(count);
            // 程序能够片跑到这，证明转账成功,将事务提交
            connection.commit();
            System.out.println("转账成功！");
        } catch (ClassNotFoundException | SQLException e) {
            System.out.println("转账失败！");
            // 手动回滚
            try {
                connection.rollback();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            if (ps != null){
                try{
                    ps.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null){
                try{
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
